package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.help.condition.ConditionHelper;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.OptionalRangeEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.PaasFormHelp;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.vo.CustomerRuleVO;
import com.xbongbong.paas.service.UserService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.PublicSeasSeniorTabEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.PublicPoolErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemLabelErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.listbatch.pojo.TeamBatchPojo;
import com.xbongbong.pro.publicgroup.pojo.PublicGroupFormTreeTwoPojo;
import com.xbongbong.pro.publicgroup.pojo.PublicGroupListPojo;
import com.xbongbong.pro.publicgroup.pojo.PublicGroupSeniorFormTreePojo;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupSeniorDeleteDTO;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupSeniorDetailDTO;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupSeniorFormListDTO;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupSeniorMoveDTO;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupSeniorSaveDTO;
import com.xbongbong.pro.publicgroup.pojo.dto.PublicGroupSortInfoDTO;
import com.xbongbong.pro.publicgroup.pojo.vo.PublicGroupFormListVO;
import com.xbongbong.pro.publicgroup.pojo.vo.PublicGroupSeniorFormListVO;
import com.xbongbong.pro.publicgroup.pojo.vo.PublicGroupSeniorItemVO;
import com.xbongbong.pro.publicgroup.pojo.vo.PublicGroupSeniorListVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ClueRuleEntity;
import com.xbongbong.saas.domain.entity.CustomerRuleEntity;
import com.xbongbong.saas.domain.entity.PublicGroupEntity;
import com.xbongbong.saas.domain.entity.PublicGroupSeniorEntity;
import com.xbongbong.saas.domain.entity.TransferBackRuleSeniorEntity;
import com.xbongbong.saas.enums.ClueRuleEnum;
import com.xbongbong.saas.enums.ClueSeniorRuleTypeEnum;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.CustomerRuleEnum;
import com.xbongbong.saas.enums.CustomerSeniorRuleTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.SeniorPublicGroupTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.help.PublicSeniorLogHelp;
import com.xbongbong.saas.help.PublicSeniorRuleHelp;
import com.xbongbong.saas.model.ClueRuleModel;
import com.xbongbong.saas.model.CustomerRuleModel;
import com.xbongbong.saas.model.PublicGroupModel;
import com.xbongbong.saas.model.PublicGroupSeniorModel;
import com.xbongbong.saas.model.TransferBackRuleSeniorModel;
import com.xbongbong.saas.service.PublicGroupSeniorService;
import com.xbongbong.saas.service.PublicGroupService;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @author lrj
 * @date 2022/4/14 14:12
 */
@Service("publicGroupSeniorService")
public class PublicGroupSeniorServiceImpl implements PublicGroupSeniorService {

    /**
     * 每个模板最多50个分组
     */
    private static final int MAX_GROUP_COUNT = 50;

    private static final Logger LOG = LoggerFactory.getLogger(PublicGroupSeniorServiceImpl.class);

    @Resource
    private PublicGroupSeniorModel publicGroupSeniorModel;

    @Resource
    private PaasFormModel paasFormModel;

    @Resource
    private CompanyConfigModel companyConfigModel;

    @Resource
    private PublicGroupModel publicGroupModel;

    @Resource
    private PaasFormHelp paasFormHelp;

    @Resource
    private CustomerRuleModel customerRuleModel;
    @Resource
    private ClueRuleModel clueRuleModel;
    @Resource
    private TransferBackRuleSeniorModel transferBackRuleSeniorModel;
    @Resource
    private PublicGroupService publicGroupService;
    @Resource
    private PublicSeniorRuleHelp publicSeniorRuleHelp;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private UserModel userModel;
    @Resource
    private UserService userService;
    @Resource
    private PublicSeniorLogHelp publicSeniorLogHelp;
    @Resource
    private CommonHelp commonHelp;

    @Resource
    private ConditionHelper conditionHelper;

    @Override
    public BaseVO add(PublicGroupSeniorSaveDTO publicGroupSeniorSaveDTO) throws XbbException {
        //todo 判断当前公司是否处于切换模式下
        BaseVO baseVO = new BaseVO();
        String corpid = publicGroupSeniorSaveDTO.getCorpid();
        String userId = publicGroupSeniorSaveDTO.getUserId();
        Integer businessType = publicGroupSeniorSaveDTO.getBusinessType();
        // 参数
        Long id = publicGroupSeniorSaveDTO.getId();
        String name = publicGroupSeniorSaveDTO.getName();
        Long formId = publicGroupSeniorSaveDTO.getFormId();
        Integer level = publicGroupSeniorSaveDTO.getLevel();
        List<OptionalRangeEntity> scopeRule = publicGroupSeniorSaveDTO.getScopeRule();
        List<OptionalRangeEntity> adminScopeRule = publicGroupSeniorSaveDTO.getAdminScopeRule();
        JSONArray jsonData = publicGroupSeniorSaveDTO.getJsonData();

        // 设置默认值
        id = id != null ? id : 0L;
        scopeRule = scopeRule != null ? scopeRule : new ArrayList<>();
        jsonData = jsonData != null ? jsonData : new JSONArray();
        boolean isNew = id <= 0L;
        PublicGroupSeniorEntity publicGroup = new PublicGroupSeniorEntity();
        PublicGroupSeniorEntity oldGroupEntity = null;
        PublicGroupSeniorEntity newGroupEntity;
        if (!isNew) {
            oldGroupEntity = publicGroupSeniorModel.getByKey(id, corpid);
            if (oldGroupEntity == null) {
                throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218007);
            }
            publicGroup.setId(id);
        }
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("corpid", corpid);
        // 每个模板最多50个分组
        param.put("formId", formId);
        List<PublicGroupSeniorEntity> groupSeniorEntities = publicGroupSeniorModel.getByGroupName(name, formId, corpid,null);
        if (isNew) {
            //新建
            int allCount = publicGroupSeniorModel.getEntitysCount(param);
            int maxNum = MAX_GROUP_COUNT;
            if (allCount >= (maxNum + 1)) {
                throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218010, PublicPoolErrorCodeEnum.API_ERROR_218010.getMsg(), maxNum);
            }
            //判断层级是否大于5
            if (level > BasicConstant.FIVE) {
                throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218012);
            }
            //查看名称是否有重复
            if (CollectionsUtil.isNotEmpty(groupSeniorEntities)) {
                throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218009);
            }
            publicGroup.setCorpid(corpid);
            publicGroup.setCreatorId(userId);
        }else {
            //查看名称是否有重复
            if (CollectionsUtil.isNotEmpty(groupSeniorEntities)) {
                for(PublicGroupSeniorEntity entity : groupSeniorEntities){
                    if(!Objects.equals(entity.getId(),id)){
                        throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218009);
                    }
                }
            }
        }
        JSONArray scopeRuleArray = new JSONArray();
        scopeRuleArray.addAll(scopeRule);
        JSONArray adminScopeRuleArray = new JSONArray();
        adminScopeRuleArray.addAll(adminScopeRule);
        JSONArray jsonDataArray = new JSONArray();
        jsonDataArray.addAll(jsonData);
        publicGroup.setName(name);
        publicGroup.setCorpid(corpid);
        publicGroup.setFormId(formId);
        publicGroup.setBusinessType(businessType);
        publicGroup.setLevel(publicGroupSeniorSaveDTO.getLevel());
        publicGroup.setParentId(publicGroupSeniorSaveDTO.getParentId());
        publicGroup.setSort(publicGroupSeniorSaveDTO.getSort());
        publicGroup.setAdminScopeRule(adminScopeRuleArray);
        publicGroup.setJsonData(jsonDataArray);
        publicGroup.setScopeRule(scopeRuleArray);
        publicGroup.setModifierId(userId);
        publicGroup.setGroupType(publicGroupSeniorSaveDTO.getGroupType());
        publicGroup.setUpdateTime((long) DateUtil.getInt());
        publicGroup.setStatus(publicGroupSeniorSaveDTO.getStatus());
        try {
            publicGroupSeniorModel.save(publicGroup);
        } catch (Exception e) {
            LOG.error("add,保存公海池分组出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        try {
            if (isNew){
                oldGroupEntity = publicGroup;
                newGroupEntity = publicGroup;
            }else {
                newGroupEntity = publicGroupSeniorModel.getByKey(id, corpid);
            }
            publicSeniorLogHelp.savePublicGroupLog(oldGroupEntity,newGroupEntity,publicGroupSeniorSaveDTO,isNew);
        } catch (Exception e) {
            LOG.error("add,保存公海池分组日志出错", e);
        }
        return baseVO;
    }

    @Override
    public BaseVO delete(PublicGroupSeniorDeleteDTO publicGroupSeniorDeleteDTO) throws XbbException {
        String corpid = publicGroupSeniorDeleteDTO.getCorpid();
        Long id = publicGroupSeniorDeleteDTO.getId();
        BaseVO baseVO = new BaseVO();
        // TODO 公海池分组设置权限
        PublicGroupSeniorEntity publicGroupSeniorEntity = publicGroupSeniorModel.getByKey(id, corpid);
        if (publicGroupSeniorEntity == null) {
            throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218007);
        }
        publicGroupSeniorEntity.setDel(DelEnum.DELETE.getDel());
        publicGroupSeniorEntity.setModifierId(publicGroupSeniorDeleteDTO.getUserId());
        publicGroupSeniorEntity.setUpdateTime((long) DateUtil.getInt());
        try {
            publicGroupSeniorModel.save(publicGroupSeniorEntity);
        } catch (Exception e) {
            LOG.error("delete，删除公海池分组出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        try {
            publicSeniorLogHelp.deletePublicGroupLog(publicGroupSeniorEntity,publicGroupSeniorDeleteDTO);
        } catch (Exception e) {
            LOG.error("delete，保存日志出错", e);
        }
        return baseVO;
    }

    @Override
    public PublicGroupSeniorItemVO getItem(PublicGroupSeniorDetailDTO publicGroupSeniorDetailDTO) throws XbbException {
        PublicGroupSeniorItemVO publicGroupSeniorItemVO = new PublicGroupSeniorItemVO();
        String corpid = publicGroupSeniorDetailDTO.getCorpid();
        Long id = publicGroupSeniorDetailDTO.getId();
        Integer businessType = publicGroupSeniorDetailDTO.getBusinessType();
        PublicGroupSeniorEntity publicGroupSeniorEntity = publicGroupSeniorModel.getByKey(id, corpid);
        if (publicGroupSeniorEntity == null) {
            throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218007);
        }
        JSONArray jsonData = publicGroupSeniorEntity.getJsonData();
        JSONArray scopeRule = publicGroupSeniorEntity.getScopeRule();
        JSONArray adminScopeRule = publicGroupSeniorEntity.getAdminScopeRule();
        if (jsonData == null) {
            jsonData = new JSONArray();
        }
        // 处理有员工或部门的筛选条件
        conditionHelper.handleUserConditions(corpid, jsonData);
        //成员处理
        List<OptionalRangeEntity> scopeRuleData;
        try {
            scopeRuleData = scopeRule.toJavaList(OptionalRangeEntity.class);
        } catch (JSONException e) {
            scopeRuleData = new ArrayList<>();
        }
        //管理员处理
        List<OptionalRangeEntity> adminScopeRuleData;
        try {
            adminScopeRuleData = adminScopeRule.toJavaList(OptionalRangeEntity.class);
        } catch (JSONException e) {
            adminScopeRuleData = new ArrayList<>();
        }
        Long formId = publicGroupSeniorEntity.getFormId();
        String formName = "";
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
        if (paasFormEntityExt != null) {
            formName = paasFormEntityExt.getName();
        }
        BeanUtil.copyProperties(publicGroupSeniorEntity, publicGroupSeniorItemVO);
        publicGroupSeniorItemVO.setFormName(formName);
        publicGroupSeniorItemVO.setJsonData(jsonData);
        publicGroupSeniorItemVO.setScopeRule(scopeRuleData);
        publicGroupSeniorItemVO.setAdminScopeRule(adminScopeRuleData);
        publicGroupSeniorItemVO.setBusinessType(businessType);
        return publicGroupSeniorItemVO;
    }

    @Override
    public BaseVO move(PublicGroupSeniorMoveDTO publicGroupSeniorMoveDTO) throws XbbException {
        BaseVO baseVO = new BaseVO();
        String corpid = publicGroupSeniorMoveDTO.getCorpid();
        List<PublicGroupSortInfoDTO> sortInfo = publicGroupSeniorMoveDTO.getSortInfo();
        List<PublicGroupSeniorEntity> sortList = new ArrayList<>();
        getSortList(sortInfo, sortList);
        if (CollectionsUtil.isNotEmpty(sortList)) {
            for (PublicGroupSeniorEntity entity : sortList) {
                if (entity.getLevel() > BasicConstant.FIVE) {
                    throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218012);
                }
            }
        }
        try {
            publicGroupSeniorModel.updateBatch(sortList, corpid);
        } catch (Exception e) {
            LOG.error("move，批量更新失败");
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        try {
            publicSeniorLogHelp.movePublicGroupLog(publicGroupSeniorMoveDTO);
        } catch (Exception e) {
            LOG.error("move，保存日志出错", e);
        }
        return baseVO;
    }

    private void getSortList(List<PublicGroupSortInfoDTO> publicGroupSortInfoDTOList, List<PublicGroupSeniorEntity> sortList) {
        for (PublicGroupSortInfoDTO publicGroupSortInfoDTO : publicGroupSortInfoDTOList) {
            PublicGroupSeniorEntity publicGroupSeniorEntity = new PublicGroupSeniorEntity();
            publicGroupSeniorEntity.setId(publicGroupSortInfoDTO.getId());
            publicGroupSeniorEntity.setSort(publicGroupSortInfoDTO.getSort());
            publicGroupSeniorEntity.setLevel(publicGroupSortInfoDTO.getLevel());
            publicGroupSeniorEntity.setParentId(publicGroupSortInfoDTO.getParentId());
            sortList.add(publicGroupSeniorEntity);
            List<PublicGroupSortInfoDTO> childList = publicGroupSortInfoDTO.getChildList();
            if (childList != null && childList.size() > 0) {
                getSortList(childList, sortList);
            }
        }
    }


    /**
     * 返回当前表单下的所有分组
     *
     * @param publicGroupSeniorDetailDTO
     * @return
     */
    @Override
    public PublicGroupSeniorListVO getByFormId(PublicGroupSeniorDetailDTO publicGroupSeniorDetailDTO) throws XbbException {
        Long formId = publicGroupSeniorDetailDTO.getFormId();
        String corpid = publicGroupSeniorDetailDTO.getCorpid();
        Integer businessType = publicGroupSeniorDetailDTO.getBusinessType();
        PublicGroupSeniorListVO publicGroupSeniorListVO = new PublicGroupSeniorListVO();
        try {
            JSONArray groupTree = publicGroupSeniorModel.getGroupTree(corpid, formId, null);
            JSONArray allGroupTree = publicSeniorRuleHelp.addFixedGroup(groupTree, true, businessType,BasicConstant.ZERO);
            publicGroupSeniorListVO.setGroupTree(allGroupTree);
        } catch (XbbException e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return publicGroupSeniorListVO;
    }

    /**
     * 左侧模板列表返回
     *
     * @param publicGroupSeniorFormListDTO
     * @return
     * @throws XbbException
     */
    @Override
    public PublicGroupSeniorFormListVO getSeniorFormList(PublicGroupSeniorFormListDTO publicGroupSeniorFormListDTO) throws XbbException {
        Integer tabType = publicGroupSeniorFormListDTO.getTabType();
        PublicGroupSeniorFormListVO publicGroupSeniorFormListVO = new PublicGroupSeniorFormListVO();
        String corpid = publicGroupSeniorFormListDTO.getCorpid();
        Integer businessType = publicGroupSeniorFormListDTO.getBusinessType();
        PublicSeasSeniorTabEnum publicSeasSeniorTabEnum = PublicSeasSeniorTabEnum.getByCode(tabType);
        UserVO loginUser = publicGroupSeniorFormListDTO.getLoginUser();
        List<CustomerRuleVO> customerRuleVOList = new ArrayList<>();
        //获得客户的全部模版
        List<PaasFormEntityExt> paasFormEntityList = paasFormModel.getEnableFormListDistributor(corpid, businessType, 0);
        if (CollectionsUtil.isEmpty(paasFormEntityList)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        List<Long> formIdList = new ArrayList<>();
        paasFormEntityList.forEach(item -> formIdList.add(item.getId()));
        List<PublicGroupSeniorFormTreePojo> formList = seniorFormList(paasFormEntityList, businessType, loginUser, corpid);
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, Integer> formIdToStatusMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("formIdIn", formIdList);
        param.put("del", BasicConstant.ZERO);
        try {
            switch (publicSeasSeniorTabEnum) {
                case PUBLIC_GROUP_RULE_SET:
                    List<PublicGroupSeniorEntity> groupSeniorEntities = publicGroupSeniorModel.findEntitys(param);
                    Map<Long, List<PublicGroupSeniorEntity>> map = groupSeniorEntities.stream().collect(Collectors.groupingBy(PublicGroupSeniorEntity::getFormId));
                    for (Map.Entry<Long, List<PublicGroupSeniorEntity>> entry : map.entrySet()) {
                        List<PublicGroupSeniorEntity> value = entry.getValue();
                        if (CollectionsUtil.isNotEmpty(value)) {
                            for (PublicGroupSeniorEntity seniorEntity : value) {
                                if (Objects.equals(seniorEntity.getGroupType(), SeniorPublicGroupTypeEnum.NO_PUBLIC_GROUP.getType())) {
                                    formIdToStatusMap.put(entry.getKey(), seniorEntity.getStatus());
                                    break;
                                }
                            }
                        }
                    }
                    break;
                case PUBLIC_BACK_RULE_SET:
                    param.put("type", CustomerSeniorRuleTypeEnum.BACK_RULE.getCode());
                    List<TransferBackRuleSeniorEntity> backRuleEntities = transferBackRuleSeniorModel.findEntitys(param);
                    formIdToStatusMap = backRuleEntities.stream().collect(Collectors.toMap(TransferBackRuleSeniorEntity::getFormId, TransferBackRuleSeniorEntity::getStatus));
                    break;
                case PUBLIC_TRANSFER_RULE_SET:
                    param.put("type", CustomerSeniorRuleTypeEnum.TRANSFER_RULE.getCode());
                    List<TransferBackRuleSeniorEntity> transferRuleEntities = transferBackRuleSeniorModel.findEntitys(param);
                    formIdToStatusMap = transferRuleEntities.stream().collect(Collectors.toMap(TransferBackRuleSeniorEntity::getFormId, TransferBackRuleSeniorEntity::getStatus));
                    break;
                case PUBLIC_OTHER_RULE_SET:
                    customerRuleVOList = getOtherSetList(corpid, businessType);
                    break;
                default:
                    break;
            }
            //获取分组、自动退回、自动转移每个模板的左侧状态
            if (formIdToStatusMap.size() > 0) {
                Map<Long, Integer> finalFormIdToStatusMap = formIdToStatusMap;
                formList.forEach(item -> item.setStatus(finalFormIdToStatusMap.getOrDefault(item.getFormId(), 0)));
            }else {
                formList.forEach(item -> item.setStatus(BasicConstant.ZERO));
            }
        } catch (Exception e) {
            LOG.error("getSeniorFormList,高级模式公海池获得表单模版出错");
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        publicGroupSeniorFormListVO.setFormList(formList);
        publicGroupSeniorFormListVO.setBusinessType(businessType);
        publicGroupSeniorFormListVO.setRuleList(customerRuleVOList);
        publicGroupSeniorFormListVO.setSaasMark(paasFormEntityList.get(0).getSaasMark());
        return publicGroupSeniorFormListVO;
    }

    private List<CustomerRuleVO> getOtherSetList(String corpid, Integer businessType) throws XbbException {
        List<CustomerRuleVO> customerRuleVOList = new ArrayList<>();

        List<TransferBackRuleSeniorEntity> typeList = transferBackRuleSeniorModel.getRuleByType(corpid, businessType);
        Map<Integer, Integer> map = typeList.stream().collect(Collectors.toMap(TransferBackRuleSeniorEntity::getType, TransferBackRuleSeniorEntity::getStatus));

        List<CustomerSeniorRuleTypeEnum> allEnum = Arrays.asList(CustomerSeniorRuleTypeEnum.MAX_CUSTOMER_NUM_RULE, CustomerSeniorRuleTypeEnum.PRE_PRINCIPAL_RULE, CustomerSeniorRuleTypeEnum.GAIN_RATE_RULE);
        for (CustomerSeniorRuleTypeEnum ruleEnum : allEnum) {
            Integer status = map.get(ruleEnum.getCode()) != null ? map.get(ruleEnum.getCode()) : BasicConstant.ZERO;
            CustomerRuleVO customerRuleVO = new CustomerRuleVO();
            customerRuleVO.setRuleType(ruleEnum.getCode());
            customerRuleVO.setStatus(status);
            if (Objects.equals(ruleEnum.getCode(), BasicConstant.THREE)) {
                if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                    customerRuleVO.setName(CustomerSeniorRuleTypeEnum.MAX_CUSTOMER_NUM_RULE.getName());
                    customerRuleVO.setTypeName(CustomerSeniorRuleTypeEnum.MAX_CUSTOMER_NUM_RULE.getName());
                } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                    customerRuleVO.setName(ClueSeniorRuleTypeEnum.MAX_CLUE_NUM_RULE.getName());
                    customerRuleVO.setTypeName(ClueSeniorRuleTypeEnum.MAX_CLUE_NUM_RULE.getName());
                }
            } else {
                customerRuleVO.setName(ruleEnum.getName());
                customerRuleVO.setTypeName(ruleEnum.getName());
            }
            customerRuleVOList.add(customerRuleVO);
        }
        //高级模式提醒时间设置
        CustomerRuleVO customerRuleVO = new CustomerRuleVO();
        Integer remindTime = getRemindTime(corpid, businessType);
        customerRuleVO.setTypeName(I18nMessageUtil.getMessage(StringConstant.PUBLIC_REMIND_SET));
        customerRuleVO.setName(I18nMessageUtil.getMessage(StringConstant.PUBLIC_REMIND_SET));
        customerRuleVO.setTip(I18nMessageUtil.getMessage(StringConstant.PUBLIC_BACK_REMIND_SET));
        customerRuleVO.setDay(remindTime);
        customerRuleVOList.add(customerRuleVO);
        return customerRuleVOList;
    }

    private List<PublicGroupSeniorFormTreePojo> seniorFormList(List<PaasFormEntityExt> paasFormEntityList, Integer businessType, UserVO loginUser, String corpid) throws XbbException {
        List<PublicGroupSeniorFormTreePojo> formList = new ArrayList<>();
        for (PaasFormEntityExt item : paasFormEntityList) {
            //过滤掉没有使用权限的SASS多模板表单
            List<OptionalRangeEntity> optionalRangeList = JSONObject.parseArray(item.getPermission(), OptionalRangeEntity.class);
            Boolean noPermission = optionalRangeList != null && !optionalRangeList.isEmpty() && paasFormHelp.haveNoPermission(loginUser, optionalRangeList);
            if (Objects.equals(item.getSaasMark(), SaasMarkEnum.SAAS.getCode()) && RedundantTemplateTypeEnum.isMultiTemplate(item.getBusinessType()) && noPermission) {
                continue;
            }
            PublicGroupSeniorFormTreePojo publicGroupSeniorFormTreePojo = new PublicGroupSeniorFormTreePojo();
            publicGroupSeniorFormTreePojo.setFormId(item.getId());
            publicGroupSeniorFormTreePojo.setName(item.getName());
            publicGroupSeniorFormTreePojo.setFormName(item.getName());
            publicGroupSeniorFormTreePojo.setAppId(item.getAppId());
            publicGroupSeniorFormTreePojo.setMenuId(item.getMenuId());
            publicGroupSeniorFormTreePojo.setBusinessType(businessType);
            formList.add(publicGroupSeniorFormTreePojo);
        }
        return formList;
    }

    /**
     * 标准模式下，左侧模板列表返回
     *
     * @param publicGroupSeniorFormListDTO
     * @return
     * @throws XbbException
     */
    @Override
    public PublicGroupFormListVO getFormList(PublicGroupSeniorFormListDTO publicGroupSeniorFormListDTO) throws XbbException {
        Integer tabType = publicGroupSeniorFormListDTO.getTabType();
        PublicGroupFormListVO publicGroupFormListVO = new PublicGroupFormListVO();
        String corpid = publicGroupSeniorFormListDTO.getCorpid();
        Integer businessType = publicGroupSeniorFormListDTO.getBusinessType();
        PublicSeasSeniorTabEnum publicSeasSeniorTabEnum = PublicSeasSeniorTabEnum.getByCode(tabType);
        //获得已启用全部模版
        List<PaasFormEntityExt> paasFormEntityList = paasFormModel.getEnableFormListDistributor(corpid, businessType, 0);
        if (CollectionsUtil.isEmpty(paasFormEntityList)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        switch (publicSeasSeniorTabEnum) {
            case PUBLIC_GROUP_RULE_SET:
                //获得模板下的分组
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("del", DelEnum.NORMAL.getDel());
                param.put("corpid", corpid);
                param.put("orderByStr", "sort desc");
                List<PublicGroupEntity> publicGroupList = publicGroupModel.findEntitys(param);
                List<PublicGroupListPojo> list = new ArrayList<>();
                for (PublicGroupEntity entity : publicGroupList) {
                    PublicGroupListPojo listPojo = new PublicGroupListPojo();
                    BeanUtil.copyProperties(entity, listPojo);
                    listPojo.setIsEnable(entity.getEnable());
                    list.add(listPojo);
                }
                List<PublicGroupFormTreeTwoPojo> formList = new ArrayList<>();
                for (PaasFormEntityExt item : paasFormEntityList) {
                    //过滤掉没有使用权限的SASS多模板表单
                    List<OptionalRangeEntity> optionalRangeList = JSONObject.parseArray(item.getPermission(), OptionalRangeEntity.class);
                    Boolean noPermission = optionalRangeList != null && !optionalRangeList.isEmpty() && paasFormHelp.haveNoPermission(publicGroupSeniorFormListDTO.getLoginUser(), optionalRangeList);
                    if (Objects.equals(item.getSaasMark(), SaasMarkEnum.SAAS.getCode()) && RedundantTemplateTypeEnum.isMultiTemplate(item.getBusinessType()) && noPermission) {
                        continue;
                    }
                    PublicGroupFormTreeTwoPojo publicGroupSeniorFormTreePojo = new PublicGroupFormTreeTwoPojo();
                    publicGroupSeniorFormTreePojo.setNode(getSubPublicGroup(item.getId(), list));
                    publicGroupSeniorFormTreePojo.setFormId(item.getId());
                    publicGroupSeniorFormTreePojo.setName(item.getName());
                    publicGroupSeniorFormTreePojo.setFormName(item.getName());
                    formList.add(publicGroupSeniorFormTreePojo);
                }
                publicGroupFormListVO.setFormList(formList);
                publicGroupFormListVO.setSaasMark(paasFormEntityList.get(0).getSaasMark());
                publicGroupFormListVO.setMenuId(paasFormEntityList.get(0).getMenuId());
                publicGroupFormListVO.setAppId(paasFormEntityList.get(0).getAppId());
                publicGroupFormListVO.setBusinessType(businessType);
                break;
            case PUBLIC_BACK_RULE_SET:
                Map<String, Object> ruleParam = new HashMap<>(4);
                List<CustomerRuleVO> backRuleVOList = new ArrayList<>();
                ruleParam.put("corpid", corpid);
                ruleParam.put("del", DelEnum.NORMAL.getDel());
                ruleParam.put("start", 0);
                ruleParam.put("pageNum", 10);
                if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                    //客户，有左侧列表     无新建跟进客户规则 ruleType 1,  无新建机会客户规则 ruleType 2,  无签订合同客户规则 ruleType 3
                    List<CustomerRuleEntity> ruleList = customerRuleModel.findEntitys(ruleParam);
                    Map<Integer, CustomerRuleEntity> ruleMap = new HashMap<>(10);
                    for (CustomerRuleEntity rule : ruleList) {
                        ruleMap.put(rule.getRuleType(), rule);
                    }
                    List<CustomerRuleEnum> enumList = Arrays.asList(CustomerRuleEnum.NO_CUSTOMER_COMMUNICATE_RULE,CustomerRuleEnum.NO_OPPORTUNITY_RULE,CustomerRuleEnum.NO_CONTRACT_RULE);
                    for (CustomerRuleEnum ruleEnum : enumList) {
                        CustomerRuleVO customerRuleVO = new CustomerRuleVO();
                        Integer ruleType = ruleEnum.getCode();
                        String typeName = ruleEnum.getName();
                        String tip = ruleEnum.getTip();
                        CustomerRuleEntity rule = ruleMap.get(ruleType);
                        if (rule != null) {
                            Integer status = rule.getStatus();
                            customerRuleVO.setStatus(status);
                        }
                        customerRuleVO.setTypeName(typeName);
                        customerRuleVO.setName(typeName);
                        customerRuleVO.setTip(tip);
                        customerRuleVO.setRuleType(ruleType);
                        backRuleVOList.add(customerRuleVO);
                    }
                } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                    //todo 线索只有一个
                    List<ClueRuleEntity> ruleList = clueRuleModel.findEntitys(ruleParam);
                    Map<Integer, ClueRuleEntity> ruleMap = new HashMap<>(10);
                    for (ClueRuleEntity rule : ruleList) {
                        if (Objects.equals(BasicConstant.ONE, rule.getRuleType())) {
                            ruleMap.put(rule.getRuleType(), rule);
                        }
                    }
                    List<ClueRuleEnum> enumList = Arrays.asList(ClueRuleEnum.NO_COMMUNICATE_RULE);
                    for (ClueRuleEnum ruleEnum : enumList) {
                        CustomerRuleVO customerRuleVO = new CustomerRuleVO();
                        Integer ruleType = ruleEnum.getCode();
                        String typeName = ruleEnum.getName();
                        String tip = ruleEnum.getTip();
                        ClueRuleEntity rule = ruleMap.get(ruleType);
                        if (rule != null) {
                            Integer status = rule.getStatus();
                            customerRuleVO.setStatus(status);
                        }
                        customerRuleVO.setTypeName(typeName);
                        customerRuleVO.setName(typeName);
                        customerRuleVO.setTip(tip);
                        customerRuleVO.setRuleType(ruleType);
                        backRuleVOList.add(customerRuleVO);
                    }
                }
                List<PublicGroupFormTreeTwoPojo> formTreeList = getFormTree(paasFormEntityList, publicGroupSeniorFormListDTO);
                publicGroupFormListVO.setRuleList(backRuleVOList);
                publicGroupFormListVO.setFormList(formTreeList);
                break;
            case PUBLIC_DISTRIBUTION_RULE_SET:
                //是自动分配,只有线索有
                break;
            case PUBLIC_OTHER_RULE_SET:
                //客户：最大拥有客户数 ruleType 4，前负责人 ruleType 5，捞取频率 ruleType 6，提醒时间
                // 线索：最大拥有线索数 ruleType 2、前负责人 ruleType 3、捞取频率 ruleType 4、提醒时间
                Integer remindTime = 3;
                List<CustomerRuleVO> rulePojos = new ArrayList<>();
                if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                    Map<String, Object> customerParam = new HashMap<>(4);
                    customerParam.put("corpid", corpid);
                    customerParam.put("del", DelEnum.NORMAL.getDel());
                    customerParam.put("start", 0);
                    customerParam.put("pageNum", 10);
                    List<CustomerRuleEntity> ruleList = customerRuleModel.findEntitys(customerParam);
                    Map<Integer, CustomerRuleEntity> ruleMap = new HashMap<>(10);
                    for (CustomerRuleEntity rule : ruleList) {
                        boolean otherFlag = Objects.equals(BasicConstant.FOUR, rule.getRuleType()) || Objects.equals(BasicConstant.FIVE, rule.getRuleType()) ||
                                Objects.equals(BasicConstant.SIX, rule.getRuleType());
                        if (otherFlag) {
                            ruleMap.put(rule.getRuleType(), rule);
                        }
                    }
                    List<CustomerRuleEnum> enumList = Arrays.asList(CustomerRuleEnum.MAX_CUSTOMER_NUM_RULE, CustomerRuleEnum.PRE_PRINCIPAL_RULE, CustomerRuleEnum.GAIN_RATE_RULE);
                    for (CustomerRuleEnum ruleEnum : enumList) {
                        CustomerRuleVO customerRuleVO = new CustomerRuleVO();
                        Integer ruleType = ruleEnum.getCode();
                        String typeName = ruleEnum.getName();
                        String tip = ruleEnum.getTip();
                        Integer status = 0;
                        CustomerRuleEntity rule = ruleMap.get(ruleType);
                        if (rule != null) {
                            status = rule.getStatus();
                        }
                        customerRuleVO.setTypeName(typeName);
                        customerRuleVO.setName(typeName);
                        customerRuleVO.setTip(tip);
                        customerRuleVO.setStatus(status);
                        customerRuleVO.setRuleType(ruleType);
                        rulePojos.add(customerRuleVO);
                    }
                    remindTime = getRemindTime(corpid, businessType);
                } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                    Map<String, Object> clueParam = new HashMap<>(4);
                    clueParam.put("corpid", corpid);
                    clueParam.put("del", DelEnum.NORMAL.getDel());
                    clueParam.put("start", 0);
                    clueParam.put("pageNum", 10);
                    List<ClueRuleEntity> ruleList = clueRuleModel.findEntitys(clueParam);
                    Map<Integer, ClueRuleEntity> ruleMap = new HashMap<>(10);
                    for (ClueRuleEntity rule : ruleList) {
                        ruleMap.put(rule.getRuleType(), rule);
                    }
                    List<ClueRuleEnum> enumList = Arrays.asList(ClueRuleEnum.MAX_CLUE_NUM_RULE, ClueRuleEnum.PRE_PRINCIPAL_RULE, ClueRuleEnum.GAIN_RATE_RULE);
                    for (ClueRuleEnum ruleEnum : enumList) {
                        CustomerRuleVO customerRuleVO = new CustomerRuleVO();
                        Integer ruleType = ruleEnum.getCode();
                        String typeName = ruleEnum.getName();
                        String tip = ruleEnum.getTip();
                        Integer status = 0;
                        ClueRuleEntity rule = ruleMap.get(ruleType);
                        if (rule != null) {
                            status = rule.getStatus();
                        }
                        customerRuleVO.setTypeName(typeName);
                        customerRuleVO.setName(typeName);
                        customerRuleVO.setTip(tip);
                        customerRuleVO.setStatus(status);
                        customerRuleVO.setRuleType(ruleType);
                        rulePojos.add(customerRuleVO);
                    }
                    remindTime = getRemindTime(corpid, businessType);
                }
                //提醒时间设置
                CustomerRuleVO customerRuleVO = new CustomerRuleVO();
                customerRuleVO.setTypeName(I18nMessageUtil.getMessage(StringConstant.PUBLIC_REMIND_SET));
                customerRuleVO.setName(I18nMessageUtil.getMessage(StringConstant.PUBLIC_REMIND_SET));
                customerRuleVO.setTip(I18nMessageUtil.getMessage(StringConstant.PUBLIC_BACK_REMIND_SET));
                customerRuleVO.setDay(remindTime);
                rulePojos.add(customerRuleVO);
                List<PublicGroupFormTreeTwoPojo> otherFormTreeList = getFormTree(paasFormEntityList, publicGroupSeniorFormListDTO);
                publicGroupFormListVO.setRuleList(rulePojos);
                publicGroupFormListVO.setFormList(otherFormTreeList);
                break;
            default:
                break;
        }
        return publicGroupFormListVO;
    }

    private Integer getRemindTime(String corpid, Integer businessType) throws XbbException {
        Integer remindTime = null;
        if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            remindTime = Integer.valueOf(CompanyConfigEnum.PUBLIC_RULE_REMIND_TIME.getValue());
            try {
                CompanyConfigEntity companyConfig = companyConfigModel.initConfigEntity(corpid,
                        CompanyConfigEnum.PUBLIC_RULE_REMIND_TIME.getAlias());
                if (companyConfig != null) {
                    remindTime = StringUtil.toInt(companyConfig.getConfigValue(), remindTime);
                }
            } catch (Exception e) {
                LOG.error("getRemindTime异常，corpid=" + corpid, e);
                throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218003);
            }
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
            remindTime = Integer.valueOf(CompanyConfigEnum.CLUE_PUBLIC_RULE_REMIND_TIME.getValue());
            try {
                CompanyConfigEntity companyConfig = companyConfigModel.initConfigEntity(corpid,
                        CompanyConfigEnum.CLUE_PUBLIC_RULE_REMIND_TIME.getAlias());
                if (companyConfig != null) {
                    remindTime = StringUtil.toInt(companyConfig.getConfigValue(), remindTime);
                }
            } catch (Exception e) {
                LOG.error("getRemindTime异常，corpid=" + corpid, e);
                throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218003);
            }

        }
        return remindTime;
    }

    private List<PublicGroupFormTreeTwoPojo> getFormTree(List<PaasFormEntityExt> paasFormEntityList, PublicGroupSeniorFormListDTO publicGroupSeniorFormListDTO) {
        Integer businessType = publicGroupSeniorFormListDTO.getBusinessType();
        List<PublicGroupFormTreeTwoPojo> formList = new ArrayList<>();
        for (PaasFormEntityExt item : paasFormEntityList) {
            //过滤掉没有使用权限的SASS多模板表单
            List<OptionalRangeEntity> optionalRangeList = JSONObject.parseArray(item.getPermission(), OptionalRangeEntity.class);
            Boolean noPermission = optionalRangeList != null && !optionalRangeList.isEmpty() && paasFormHelp.haveNoPermission(publicGroupSeniorFormListDTO.getLoginUser(), optionalRangeList);
            if (Objects.equals(item.getSaasMark(), SaasMarkEnum.SAAS.getCode()) && RedundantTemplateTypeEnum.isMultiTemplate(item.getBusinessType()) && noPermission) {
                continue;
            }
            PublicGroupFormTreeTwoPojo publicGroupSeniorFormTreePojo = new PublicGroupFormTreeTwoPojo();
            publicGroupSeniorFormTreePojo.setFormId(item.getId());
            publicGroupSeniorFormTreePojo.setName(item.getName());
            publicGroupSeniorFormTreePojo.setFormName(item.getName());
            publicGroupSeniorFormTreePojo.setAppId(item.getAppId());
            publicGroupSeniorFormTreePojo.setMenuId(item.getMenuId());
            publicGroupSeniorFormTreePojo.setBusinessType(businessType);
            publicGroupSeniorFormTreePojo.setDistributorMark(item.getDistributorMark());
            formList.add(publicGroupSeniorFormTreePojo);
        }
        return formList;
    }

    private List<PublicGroupListPojo> getSubPublicGroup(long formId, List<PublicGroupListPojo> list) {
        List<PublicGroupListPojo> pojoList = new ArrayList<>();
        for (PublicGroupListPojo pojo : list) {
            if (pojo.getFormId() == formId) {
                PublicGroupListPojo newPojo = new PublicGroupListPojo();
                BeanUtil.copyProperties(pojo, newPojo);
                pojoList.add(newPojo);
            }
        }
        return pojoList;
    }

    /**
     * 返回 Map形式
     *
     * @author lijiangren
     * @date 2022-04-20 14 53
     */
    @Override
    public Map<Long, PublicGroupSeniorEntity> getPublicGroupMap(Long formId, String corpid) {
        Map<Long, PublicGroupSeniorEntity> publicGroupMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<PublicGroupSeniorEntity> seniorEntityList = publicGroupSeniorModel.getByFormId(formId, corpid, BasicConstant.ZERO);
        if (CollectionUtils.isEmpty(seniorEntityList)) {
            return publicGroupMap;
        }
        Map<Long, PublicGroupSeniorEntity> publicGroupSeniorMap = seniorEntityList.stream().
                collect(Collectors.toMap(PublicGroupSeniorEntity::getId, publicGroupSeniorEntity -> publicGroupSeniorEntity));
        return publicGroupSeniorMap;
    }

    /**
     * 单条数据分组id 转化为分组名称
     *
     * @param groupAttr
     * @param dataJsonObject
     */
    @Override
    public void dealId2GroupName(String groupAttr, JSONObject dataJsonObject, Map<Long, PublicGroupSeniorEntity> publicGroupSeniorMap) throws XbbException {
        try {
            if (publicGroupSeniorMap != null && publicGroupSeniorMap.size() > 0) {
                if (StringUtil.isNotEmpty(groupAttr)) {
                    // 查询对应的标签
                    String groupIdStr = dataJsonObject.getString(groupAttr);
                    if (StringUtil.isNotEmpty(groupIdStr)) {
                        PublicGroupSeniorEntity publicGroupSeniorEntity = publicGroupSeniorMap.get(Long.valueOf(groupIdStr));
                        if (Objects.nonNull(publicGroupSeniorEntity)) {
                            dataJsonObject.put(groupAttr, publicGroupSeniorEntity.getName());
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("分组转化失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 根据优先级规则处理分组失败
     *
     * @param corpid
     * @param formId
     * @author lijiangren
     * @date 2022-05-16 09 30
     */
    @Override
    public List<PublicGroupSeniorEntity> getFormListByPriority(String corpid, Long formId) throws XbbException {
        try {
            Map param= new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("formId", formId);
            param.put("del", DelEnum.NORMAL.getDel());
            param.put("status", BasicConstant.ONE);
            List<PublicGroupSeniorEntity> allGroupList = publicGroupSeniorModel.findEntitys(param);
            List<PublicGroupSeniorEntity> resultList = new ArrayList<>();
            //层级最大只能建五层
            Integer levelMax = BasicConstant.FIVE;
            for (Integer level = levelMax; level >= 0; level--) {
                if (CollectionsUtil.isNotEmpty(allGroupList)) {
                    Integer finalLevel = level;
                    List<PublicGroupSeniorEntity> collect = allGroupList.stream().filter(item -> Objects.equals(item.getLevel(), finalLevel)).collect(Collectors.toList());
                    if (CollectionsUtil.isNotEmpty(collect)) {
                        Map<Long, List<PublicGroupSeniorEntity>> collectMap = collect.stream().filter(item -> Objects.nonNull(item.getParentId()) && Objects.equals(item.getGroupType(), SeniorPublicGroupTypeEnum.OTHER_PUBLIC_GROUP.getType())).collect(Collectors.groupingBy(t -> t.getParentId()));
                        if (collectMap.size() == 1) {
                            Set<Long> keySet = collectMap.keySet();
                            for (Long aLong : keySet) {
                                List<PublicGroupSeniorEntity> publicGroupSeniorEntities = collectMap.get(aLong);
                                if (CollectionsUtil.isNotEmpty(publicGroupSeniorEntities)) {
                                    publicGroupSeniorEntities.sort((s1, s2) -> s1.getSort().compareTo(s2.getSort()));
                                    resultList.addAll(publicGroupSeniorEntities);
                                }
                            }
                        } else {
                            Set<Long> longs = collectMap.keySet();
                            List<PublicGroupSeniorEntity> sortAsc = allGroupList.stream().filter(item -> longs.contains(item.getId())).collect(Collectors.toList());
                            sortAsc.sort((s1, s2) -> s1.getSort().compareTo(s2.getSort()));
                            for (PublicGroupSeniorEntity publicGroupSeniorEntity : sortAsc) {
                                resultList.addAll(collectMap.get(publicGroupSeniorEntity.getId()));
                            }
                        }
                    }
                }
            }

            PublicGroupSeniorEntity noPublicGroup = allGroupList.stream().filter(item -> Objects.equals(item.getGroupType(), SeniorPublicGroupTypeEnum.NO_PUBLIC_GROUP.getType())).findAny().orElse(null);
            if (Objects.nonNull(noPublicGroup)) {
                resultList.add(noPublicGroup);
            }
            return resultList;
        } catch (Exception e) {
            LOG.error("根据优先级规则处理分组失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 通过登录人匹配高级分组的管理员权限字段过滤分组
     *
     * @author lijiangren
     * @date 2022-06-02 10 23
     */
    @Override
    public List<PublicGroupSeniorEntity> filterGroupSeniorByAdminScopeRule(List<PublicGroupSeniorEntity> list, UserEntity user) {
        List<PublicGroupSeniorEntity> resultList = new ArrayList<>();
        // 角色数据
        List<Integer> roleIds = user.roleIdsToList();
        // 部门列表
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", user.getCorpid());
        param.put("del", DelEnum.NORMAL.getDel());
        List<DepartmentEntity> allDepartmentList = departmentModel.findEntitys(param);
        // 获得用户所属部门id列表
        List<Long> belongDepList = userModel.getUserBelongDeptIdList(user, false);

        for (PublicGroupSeniorEntity entity : list) {
            JSONArray adminScopeRule = entity.getAdminScopeRule();
            List<OptionalRangeEntity> adminScopeRuleData;
            try {
                adminScopeRuleData = adminScopeRule.toJavaList(OptionalRangeEntity.class);
            } catch (JSONException e) {
                adminScopeRuleData = new ArrayList<>();
            }
            // 未设置查看权限
            if (adminScopeRuleData.size() <= 0) {
                //resultList.add(entity);
                continue;
            }

            List<Long> depIdArray = new ArrayList<>();
            List<Integer> roleIdArray = new ArrayList<>();
            List<String> userIdArray = new ArrayList<>();

            //有管理员权限也可以查看该分组
            for (OptionalRangeEntity rangeEntity : adminScopeRuleData) {
                String property = rangeEntity.getProperty();
                String id = rangeEntity.getId();

                if (OptionalRangeEnum.DEPT.getValue().equals(property)) {
                    depIdArray.add(Long.parseLong(id));
                } else if (OptionalRangeEnum.ROLE.getValue().equals(property)) {
                    roleIdArray.add(Integer.parseInt(id));
                } else if (OptionalRangeEnum.USER.getValue().equals(property)) {
                    userIdArray.add(id);
                }
            }

            // 未设置查看权限
            if (depIdArray.isEmpty() && roleIdArray.isEmpty() && userIdArray.isEmpty()) {
                resultList.add(entity);
                continue;
            }

            // 角色是否有交集
            roleIdArray.retainAll(roleIds);
            if (!roleIdArray.isEmpty()) {
                resultList.add(entity);
                continue;
            }

            // 全公司
            if (depIdArray.contains(1L)) {
                resultList.add(entity);
                continue;
            }

            // 获取有权限查看模板的部门以及子部门
            Set<Long> depIncludeSubSet = new LinkedHashSet<>();
            for (Long depId : depIdArray) {
                Set<Long> subDepIdList = userService.getSubDepIdList(depId, allDepartmentList);
                depIncludeSubSet.addAll(subDepIdList);
            }
            depIncludeSubSet.retainAll(belongDepList);
            if (!depIncludeSubSet.isEmpty()) {
                resultList.add(entity);
                continue;
            }

            // 自定义人员匹配
            if (userIdArray.contains(user.getUserId())) {
                resultList.add(entity);
            }

        }
        return resultList;
    }

    @Override
    public List<TeamBatchPojo> publicGroupVerify(String corpid, Integer businessType, Long formId, String oprateTagName, UserVO loginUser, List<PaasFormDataEntityExt> list, List<Long> dataIdList) {
        //异常信息封装
        List<TeamBatchPojo> teamBatchPojos = new ArrayList<>();
        try {
            boolean publicPoolSeniorModel = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
            if (Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())) {
                publicPoolSeniorModel = commonHelp.isCluePublicPoolSeniorModel(corpid);
            }
            if (publicPoolSeniorModel) {
                UserEntity userEntity = new UserEntity();
                BeanUtil.copyProperties(loginUser, userEntity);
                boolean isBoss = loginUser.isAdminOrBoss();
                boolean maxDataPermission = loginUser.isMaxDataPermission();
                if (!isBoss && !maxDataPermission) {
                //if (true) {
                    String businessName = XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getName();
                    String groupAttr = CustomerManagementEnum.PUBLIC_GROUP.getAttr();
                    String nameAttr = CustomerManagementEnum.NAME.getAttr();
                    if (Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())) {
                        businessName = XbbRefTypeEnum.CLUE.getName();
                        groupAttr = ClueEnum.PUBLIC_GROUP.getAttr();
                        nameAttr = ClueEnum.COMPANY_NAME.getAttr();
                    }

                    List<Long> groupSeniorIdList = new ArrayList<>();
                    //过滤出来需要判断的分组权限
                    for (PaasFormDataEntityExt paasFormDataEntityExt : list) {
                        JSONObject jsonObject = JSON.parseObject(paasFormDataEntityExt.getData().toJSONString());
                        String publicGroup = jsonObject.getString(groupAttr);
                        if (Objects.nonNull(publicGroup)) {
                            groupSeniorIdList.add(Long.valueOf(publicGroup));
                        }
                    }

                    if (CollectionsUtil.isNotEmpty(groupSeniorIdList)) {
                        Map<String,Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        paramMap.put("corpid",corpid);
                        paramMap.put("idIn",groupSeniorIdList);
                        paramMap.put("status",BasicConstant.ONE);
                        paramMap.put("orderByStr","sort asc");
                        List<PublicGroupSeniorEntity> publicGroupSeniorEntityList = publicGroupSeniorModel.findEntitys(paramMap);
                        //权限过滤处理(公海管理员权限)
                        List<PublicGroupSeniorEntity> newPublicGroupSeniorEntityList = filterGroupSeniorByAdminScopeRule(publicGroupSeniorEntityList, userEntity);
                        List<Long> groupIdList = newPublicGroupSeniorEntityList.stream().map(PublicGroupSeniorEntity::getId).collect(Collectors.toList());
                        for (PaasFormDataEntityExt paasFormDataEntityExt : list) {
                            JSONObject jsonObject = JSON.parseObject(paasFormDataEntityExt.getData().toJSONString());
                            String publicGroup = jsonObject.getString(groupAttr);
                            String name = jsonObject.getString(nameAttr);
                            if (StringUtil.isNotEmpty(publicGroup)) {
                                if (!groupIdList.contains(Long.valueOf(publicGroup))) {
                                    //if (true) {
                                    //移除无权限数据
                                    dataIdList.remove(paasFormDataEntityExt.getDataId());
                                    //封装异常信息
                                    TeamBatchPojo teamBatchPojo = new TeamBatchPojo();
                                    teamBatchPojo.setCode(SystemLabelErrorCodeEnum.API_ERROR_1120031.getCode());
                                    teamBatchPojo.setFailMsgReason(String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.NO_PUBLIC_GROUP_PERMISSION), businessName, oprateTagName));
                                    teamBatchPojo.setErrorName(name);
                                    teamBatchPojo.setBasicOperate(oprateTagName);
                                    teamBatchPojo.setDataId(paasFormDataEntityExt.getDataId());
                                    teamBatchPojos.add(teamBatchPojo);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("校验公海分组出错corpid:{},异常信息：{}", corpid, e);
        }
        return teamBatchPojos;
    }
}
